/**
 * Created by jerry on 2017/6/9.
 */
import axios from 'axios'
import {bus} from '../bus.js'
import util from '../common/util'
axios.defaults.withCredentials = true;
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';//配置请求头

//添加一个请求拦截器
// axios.interceptors.request.use(function (config) {
//   console.dir(config);
//   return config;
// }, function (error) {
//   // Do something with request error
//   return Promise.reject(error);
// });

// 添加一个响应拦截器
axios.interceptors.response.use(function (response) {
  if (response.data && response.data.errcode) {
    if (parseInt(response.data.errcode) === 40001) {
      //未登录
      bus.$emit('goto', '/login')
    }
  }

  return response;
}, function (error) {
  // Do something with response error
  return Promise.reject(error);
});


export const buildRequestUrl=(url)=>{
  let params = {};

  params._trace = util.getUid();
  params._platform="web"

  let user =JSON.parse(localStorage.getItem('access-user'))
  if (user) {
    params._token = user.token;
    params._uid = user.uid
  } else {
    params._token = "";
  }


  url += "?";
  for (var k in params) {  //通过定义一个局部变量k遍历获取到了map中所有的key值
    var value = params[k]; //获取到了key所对应的value的值！
    url += k + "=" + encodeURI(value) + "&";
  }

  return url;
}

//基地址
let base = '/api/v2/admin';   //接口代理地址参见：config/index.js中的proxyTable配置

//通用方法
export const POST = (url, params) => {
  console.log('请求链接',base)
  return axios.post(`${base}`+buildRequestUrl(url), params).then(res => res.data)
}

export const GET = (url, params) => {
  return axios.get(`${base}`+buildRequestUrl(url), {params: params}).then(res => res.data)
}

export const PUT = (url, params) => {
  return axios.put(`${base}${url}`, params).then(res => res.data)
}

export const DELETE = (url, params) => {
  return axios.delete(`${base}${url}`, {params: params}).then(res => res.data)
}

export const PATCH = (url, params) => {
  return axios.patch(`${base}${url}`, params).then(res => res.data)
}
